#include "win_base.hpp"

WinBase::WinBase(QWidget* parent, const std::string& name_)
    :QMainWindow(parent)
    , name(name_)
    , logger(spdlog::default_logger())
    , pg_container(nullptr)
{
    init_ui();
    init_style();
    logger->info("window {} inited", name);
}

WinBase::~WinBase()
{
    delete wg_loading;
}

void WinBase::init_ui() 
{
    setWindowIcon(QIcon(":/images/logo.png"));
    wg_loading = new WgLoading();
}

void WinBase::init_style()
{
    QString qss_style;
    if(SgtStyle::getInstance()->get_style(qss_style,SgtStyle::SORT::GLOBAL)){
        setStyleSheet(qss_style);
    }
}

void WinBase::loading_end()
{
    wg_loading->close();
}

void WinBase::loading(const QString tips)
{
    wg_loading->set_txt_tips(tips);
    wg_loading->exec();
}

void WinBase::set_pg_container(QVBoxLayout* pg_container_)
{
    pg_container = pg_container_;
}

void WinBase::page_add(const QString key, PgBase* page)
{
    page->hide();
    pages[key] = page;
}

void WinBase::page_add(QPushButton* btn, PgBase* page)
{
    page->hide();
    connect(btn, SIGNAL(clicked()), this, SLOT(slot_page_switch()));
    connect(page, &PgBase::sigReqLoading, this, &WinBase::slot_loading);
    connect(page, &PgBase::sigReqLoadingEnd, this, &WinBase::slot_loading_end);
    pages[btn->objectName()] = page;
}

void WinBase::page_reset()
{
    std::map<QString, PgBase*>::iterator iter;
    for (iter = pages.begin(); iter != pages.end(); iter++){
        iter->second->hide();
        pg_container->removeWidget(iter->second);
    }
}

void WinBase::page_show(const QString key)
{
    if (nullptr == pg_container) {
        qt::msg::warn("page container not set");
        return;
    }
    if (pages.find(key) == pages.end()) {
        qt::msg::warn("the page not exsit");
        return;
    }
    logger->info("page show {}", key.toStdString());
    page_reset();
    pages[key]->show();
    pg_container->addWidget(pages[key]);
}

void WinBase::slot_page_switch()
{
    QPushButton* btn = (QPushButton*)sender();
    logger->info("button name {}", btn->objectName().toStdString());
    page_show(btn->objectName());
}

void WinBase::slot_loading(const QString tips)
{
    loading(tips);
}

void WinBase::slot_loading_end()
{
    loading_end();
}